package org.linlinjava.litemall.wx.web;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.exception.BusinessException;
import org.linlinjava.litemall.core.exception.ResultError;
import org.linlinjava.litemall.core.system.SystemConfig;
import org.linlinjava.litemall.core.util.JsonResponse;
import org.linlinjava.litemall.core.util.RegexUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallAddress;
import org.linlinjava.litemall.db.service.AddressService;
import org.linlinjava.litemall.db.service.RegionService;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.linlinjava.litemall.wx.service.GetRegionService;
import org.linlinjava.litemall.wx.util.CloneUtil;
import org.linlinjava.litemall.wx.vo.DefaultInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * 用户收货地址服务
 */
@RestController
@RequestMapping("/wx/address")
@Validated
@Api("用户收货地址服务")
public class WxAddressController extends GetRegionService {
	private final Log logger = LogFactory.getLog(WxAddressController.class);

	@Autowired
	private AddressService addressService;

	@Autowired
	private RegionService regionService;


	/**
	 * 用户收货地址列表
	 *
	 * @param userId 用户ID
	 * @return 收货地址列表
	 */
	@GetMapping("list")
	@ApiOperation("用户收货地址列表")
	public Object list(Integer userId) {
		if (userId == null) {
			return ResponseUtil.unlogin();
		}
		List<LitemallAddress> addressList = addressService.queryByUid(userId);
		return ResponseUtil.okList(addressList);
	}

	@GetMapping("default")
	@ApiOperation("获取默认的下单页面信息地址、运费")
	public JsonResponse<DefaultInfoVo> defaultAddress(Integer userId) {
		LitemallAddress aDefault = addressService.findDefault(userId);
		DefaultInfoVo clone;
		if (Objects.isNull(aDefault)) {
			clone = new DefaultInfoVo();
			clone.setAddressDetail("");
			clone.setName("");
			clone.setTel("");
			clone.setProvince("");
			clone.setCity("");
			clone.setCounty("");
		} else {
			clone = CloneUtil.clone(aDefault, DefaultInfoVo.class);
		}
		clone.setFreight(BigDecimal.ZERO);
//		clone.setFreight(SystemConfig.getFreight());
		return JsonResponse.ok(clone);
	}

	/**
	 * 收货地址详情
	 *
	 * @param userId 用户ID
	 * @param id     收货地址ID
	 * @return 收货地址详情
	 */
	@GetMapping("detail")
	@ApiOperation("收货地址详情")
	public Object detail(Integer userId, @NotNull Integer id) {
		if (userId == null) {
			return ResponseUtil.unlogin();
		}

		LitemallAddress address = addressService.query(userId, id);
		if (address == null) {
			return ResponseUtil.badArgumentValue();
		}
		return ResponseUtil.ok(address);
	}

	private Object validate(LitemallAddress address) {
		String name = address.getName();
		if (StringUtils.isEmpty(name)) {
			throw BusinessException.create("收件人不能为空");
		}

		// 测试收货手机号码是否正确
		String mobile = address.getTel();
		if (StringUtils.isEmpty(mobile)) {
			throw BusinessException.create("联系电话不能为空");
		}
		if (!RegexUtil.isMobileSimple(mobile)) {
			throw BusinessException.create("联系电话格式不对");
		}

		String province = address.getProvince();
		String city = address.getCity();
		String county = address.getCounty();
		if (StringUtils.isEmpty(province) || StringUtils.isEmpty(city) || StringUtils.isEmpty(county)) {
			throw BusinessException.create("地区不能为空");
		}

		String detailedAddress = address.getAddressDetail();
		if (StringUtils.isEmpty(detailedAddress)) {
			throw BusinessException.create("详细地址不能为空");
		}

		return null;
	}

	/**
	 * 添加或更新收货地址
	 *
	 * @param userId  用户ID
	 * @param address 用户收货地址
	 * @return 添加或更新操作结果
	 */
	@PostMapping("save")
	@ApiOperation("添加或更新收货地址")
	public Object save(@LoginUser Integer userId, @RequestBody LitemallAddress address) {
		if (userId == null) {
			return ResponseUtil.unlogin();
		}
		Object error = validate(address);
		if (error != null) {
			throw BusinessException.create("系统开小差了");
		}

		if (address.getId() == null || address.getId().equals(0)) {
			if (address.getIsDefault()) {
				// 重置其他收货地址的默认选项
				addressService.resetDefault(userId);
			}

			address.setId(null);
			address.setUserId(userId);
			addressService.add(address);
		} else {
			LitemallAddress litemallAddress = addressService.query(userId, address.getId());
			if (litemallAddress == null) {
				return ResponseUtil.badArgumentValue();
			}

			if (address.getIsDefault()) {
				// 重置其他收货地址的默认选项
				addressService.resetDefault(userId);
			}
			address.setUpdateTime(LocalDateTime.now());
			address.setUserId(userId);
			addressService.update(address);
		}
		return ResponseUtil.ok(address.getId());
	}

	/**
	 * 删除收货地址
	 *
	 * @param userId  用户ID
	 * @param addressId 地址id
	 * @return 删除操作结果
	 */
	@GetMapping("delete")
	@ApiOperation("删除收货地址")
	public JsonResponse delete(@LoginUser Integer userId, Integer addressId) {
		if (userId == null) {
			return JsonResponse.error("请登录");
		}
		if (addressId == null) {
			return JsonResponse.error("地址id不能为空");
		}
		LitemallAddress litemallAddress = addressService.query(userId, addressId);
		if (litemallAddress == null) {
			return JsonResponse.error("无法获取到当前地址");
		}

		addressService.delete(addressId);
		return JsonResponse.ok("删除成功");
	}
}
